/**
 * Author:王召波
 * E-mail:963087326@qq.com
 */
$().ready(function () {
    //所有的删除操作，删除数据后刷新页面
    if ($('a.js-ajax-dialog').length) {
        $('.js-ajax-dialog').on('click', function (e) {
            e.preventDefault();
            var $_this  = this,
                $this   = $($_this),
                href    = $this.data('href'),
                refresh = $this.data('refresh'),
                msg     = $this.data('msg');
                href    = href ? href : $this.attr('href');

            layer.confirm(msg ? msg : '确定要删除吗？', {
                btn: ['确定','取消'],icon: 3,title:''
            }, function(){
                $.getJSON(href).done(function (data) {
                    if (data.code == '1') {
                        layer.msg(data.msg, {
                            icon: 1,
                            time: 800
                        }, function(){
                            //do something
                            if (refresh == undefined || refresh) {
                                if (data.url) {
                                    console.log(1);
                                    //返回带跳转地址
                                    window.location.href = data.url;
                                } else {
                                    console.log(2);
                                    //刷新当前页
                                    reloadPage(window);
                                }
                            }
                        });
                    } else if (data.code == '0') {
                        layer.alert(data.msg, {title:''},function(index){
                            //do something
                            layer.close(index);
                        });

                    }
                });

            });


        });
    }
    // 所有的ajax form提交,由于大多业务逻辑都是一样的，故统一处理
    var ajaxForm_list = $('form.js-ajax-form');
    if (ajaxForm_list.length) {
        var $btn;
        $('button.js-ajax-submit').on('click', function (e) {
            var btn = $(this), form = btn.parents('form.js-ajax-form');
            $btn    = btn;
            if (btn.data("loading")) {
                return;
            }
            //批量操作 判断选项
            if (btn.data('subcheck')) {
                btn.parent().find('span').remove();
                if (form.find('input.js-check:checked').length) {
                    btn.data('subcheck', false);
                } else {
                    layer.msg('请至少选择一项');
                    return false;
                }
            }

            //ie处理placeholder提交问题
            if ($.browser && $.browser.msie) {
                form.find('[placeholder]').each(function () {
                    var input = $(this);
                    if (input.val() == input.attr('placeholder')) {
                        input.val('');
                    }
                });
            }
        });

        ajaxForm_list.each(function () {
            $(this).validate({
                //是否在获取焦点时验证
                //onfocusout : false,
                //是否在敲击键盘时验证
                //onkeyup : false,
                //当鼠标点击时验证
                //onclick : false,
                //给未通过验证的元素加效果,闪烁等
                highlight: function (element, errorClass, validClass) {
                    if (element.type === "radio") {
                        this.findByName(element.name).addClass(errorClass).removeClass(validClass);
                    } else {
                        var $element = $(element);
                        $element.addClass(errorClass).removeClass(validClass);
                        $element.parent().addClass("has-error");//bootstrap3表单
                        $element.parents('.control-group').addClass("error");//bootstrap2表单

                    }
                },
                unhighlight: function (element, errorClass, validClass) {
                    if (element.type === "radio") {
                        this.findByName(element.name).removeClass(errorClass).addClass(validClass);
                    } else {
                        var $element = $(element);
                        $element.removeClass(errorClass).addClass(validClass);
                        $element.parent().removeClass("has-error");//bootstrap3表单
                        $element.parents('.control-group').removeClass("error");//bootstrap2表单
                    }
                },
                showErrors: function (errorMap, errorArr) {
                    var i, elements, error;
                    for (i = 0; this.errorList[i]; i++) {
                        error = this.errorList[i];
                        if (this.settings.highlight) {
                            this.settings.highlight.call(this, error.element, this.settings.errorClass, this.settings.validClass);
                        }
                        this.showLabel( error.element, error.message );
                    }
                    if (this.errorList.length) {
                        //this.toShow = this.toShow.add( this.containers );
                    }
                    if (this.settings.success) {
                        for (i = 0; this.successList[i]; i++) {
                            //this.showLabel( this.successList[ i ] );
                        }
                    }
                    if (this.settings.unhighlight) {
                        for (i = 0, elements = this.validElements(); elements[i]; i++) {
                            this.settings.unhighlight.call(this, elements[i], this.settings.errorClass, this.settings.validClass);
                        }
                    }
                    this.toHide = this.toHide.not(this.toShow);
                    this.hideErrors();
                    this.addWrapper(this.toShow).show();
                },
                submitHandler: function (form) {
                    var $form = $(form);
                    $form.ajaxSubmit({
                        url: $btn.data('action') ? $btn.data('action') : $form.attr('action'), //按钮上是否自定义提交地址(多按钮情况)
                        dataType: 'json',
                        beforeSubmit: function (arr, $form, options) {

                            $btn.data("loading", true);
                            var text = $btn.text();

                            //按钮文案、状态修改
                            $btn.text(text + '...').prop('disabled', true).addClass('disabled');
                        },
                        success: function (data, statusText, xhr, $form) {

                            function _refresh() {
                                if (data.url) {
                                    //返回带跳转地址
                                    window.location.href = data.url;
                                } else {
                                    if (data.code == 1) {
                                        //刷新当前页
                                        reloadPage(window);
                                    }
                                }
                            }

                            var text = $btn.text();

                            //按钮文案、状态修改
                            $btn.removeClass('disabled').prop('disabled', false).text(text.replace('...', '')).parent().find('span').remove();
                            if (data.code == 1) {
                                if ($btn.data('success')) {
                                    var successCallback = $btn.data('success');
                                    window[successCallback](data, statusText, xhr, $form);
                                    return;
                                }
                                layer.msg(data.msg, {
                                    icon: 1,
                                    time: 2000 //2秒关闭（如果不配置，默认是3秒）
                                }, function(){
                                    //do something
                                    if ($btn.data('refresh') == undefined || $btn.data('refresh')) {
                                        if ($btn.data('success_refresh')) {
                                            var successRefreshCallback = $btn.data('success_refresh');
                                            window[successRefreshCallback](data, statusText, xhr, $form);
                                            return;
                                        } else {
                                            _refresh();
                                        }

                                    }
                                });
                                $(window).focus();
                            } else if (data.code == 0) {
                                var $verify_img = $form.find(".verify_img");
                                if ($verify_img.length) {
                                    $verify_img.attr("src", $verify_img.attr("src") + "&refresh=" + Math.random());
                                }

                                var $verify_input = $form.find("[name='verify']");
                                $verify_input.val("");

                                //$('<span class="tips_error">' + data.msg + '</span>').appendTo($btn.parent()).fadeIn('fast');
                                $btn.removeAttr('disabled').removeClass('disabled');

                                layer.msg(data.msg, {
                                    icon: 2,
                                    time: 2000 //2秒关闭（如果不配置，默认是3秒）
                                }, function(){
                                    //do something
                                    _refresh();
                                });
                                $(window).focus();
                            }
                        },
                        error: function (xhr, e, statusText) {
                            layer.alert(statusText, function(index){
                                //do something
                                layer.close(index);
                                reloadPage(window);
                            });

                        },
                        complete: function () {
                            $btn.data("loading", false);
                        }
                    });
                }
            });
        });
    }
    /*复选框全选(支持多个，纵横双控全选)。
     *实例：版块编辑-权限相关（双控），验证机制-验证策略（单控）
     *说明：
     *	"js-check"的"data-xid"对应其左侧"js-check-all"的"data-checklist"；
     *	"js-check"的"data-yid"对应其上方"js-check-all"的"data-checklist"；
     *	全选框的"data-direction"代表其控制的全选方向(x或y)；
     *	"js-check-wrap"同一块全选操作区域的父标签class，多个调用考虑
     */

    if ($('.js-check-wrap').length) {
        var total_check_all = $('input.js-check-all');

        //遍历所有全选框
        $.each(total_check_all, function () {
            var check_all = $(this),
                check_items;

            //分组各纵横项
            var check_all_direction = check_all.data('direction');
            check_items             = $('input.js-check[data-' + check_all_direction + 'id="' + check_all.data('checklist') + '"]').not(":disabled");

            //点击全选框
            check_all.change(function (e) {
                var check_wrap = check_all.parents('.js-check-wrap'); //当前操作区域所有复选框的父标签（重用考虑）

                if ($(this).prop('checked')) {
                    //全选状态
                    check_items.prop('checked', true);

                    //所有项都被选中
                    if (check_wrap.find('input.js-check').length === check_wrap.find('input.js-check:checked').length) {
                        check_wrap.find(total_check_all).prop('checked', true);
                    }

                } else {
                    //非全选状态
                    check_items.removeAttr('checked');

                    check_wrap.find(total_check_all).removeAttr('checked');

                    //另一方向的全选框取消全选状态
                    var direction_invert = check_all_direction === 'x' ? 'y' : 'x';
                    check_wrap.find($('input.js-check-all[data-direction="' + direction_invert + '"]')).removeAttr('checked');
                }

            });

            //点击非全选时判断是否全部勾选
            check_items.change(function () {

                if ($(this).prop('checked')) {

                    if (check_items.filter(':checked').length === check_items.length) {
                        //已选择和未选择的复选框数相等
                        check_all.prop('checked', true);
                    }

                } else {
                    check_all.removeAttr('checked');
                }

            });


        });

    }
    //返回
    if($(".back").length>0){
        var back_all = $(".back");
        $.each(back_all,function(){
            $(this).click(function(){
                var url = $(this).data('action');
                if(url){
                    window.location.href = url;
                }else{
                    window.history.back();
                }
            });

        })
    }
    if($(".viewer").length>0){
        console.log(1);
        $(".viewer").viewer();
    }

});
//重新刷新页面，使用location.reload()有可能导致重新提交
function reloadPage(win) {
    var location  = win.location;
    location.href = location.pathname + location.search;
}